// pages/category/category.js
// 导入获取数据的方法
import { request } from '../../request/index.js'
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 左侧商品列表数据
        leftMenuList: [],
        // 右侧商品数据
        rightCates: [],
        // 当前选中的index
        currentIndex: 0,
        // 右侧商品栏距离顶部的距离
        scrollTop: 0
    },
    // 接口返回的数据
    Cates: [],
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function () {
        // 判断本地存储中是否有旧数据
        const Cates = wx.getStorageSync('cates')
        if (!Cates) {
            this.getCates()

        } else {
            if (Date.now() - Cates.time > 1000 * 300) {
                this.getCates()

            } else {
                this.Cates = Cates.data
                let leftMenuList = this.Cates.map(v => v.cat_name)
                let rightCates = this.Cates[0].children
                this.setData({
                    leftMenuList,

                    rightCates

                })
            }
        }
    },
    async getCates() {
        // request({ url: '/categories' }).then(result => {
        //     this.Cates = result.data.message
        //     // 把获取到的数据存储到本地存储中
        //     wx.setStorageSync('cates', { time: Date.now(), data: this.Cates })
        //     let leftMenuList = this.Cates.map(v => v.cat_name)
        //     let rightCates = this.Cates[0].children
        //     this.setData({
        //         leftMenuList,

        //         rightCates

        //     })
        //     console.log(result);
        // })
        const result = await request({ url: '/categories' })
        this.Cates = result
        // 把获取到的数据存储到本地存储中
        wx.setStorageSync('cates', { time: Date.now(), data: this.Cates })
        let leftMenuList = this.Cates.map(v => v.cat_name)
        let rightCates = this.Cates[0].children
        this.setData({
            leftMenuList,

            rightCates

        })
    },
    handleItemTap(e) {
        // 获取被点击菜单的索引值
        const { index } = e.currentTarget.dataset
        // 根据不同索引渲染不同的内容
        let rightCates = this.Cates[index].children
        this.setData({
            currentIndex: index,
            scrollTop: 0,
            rightCates

        })
    }
})